<?php
class permissionsControl extends module {
	public $permissions = array('*'=>array(ROLE_ADMIN, ROLE_SUPERADMIN));
	public $title = "Permissions control";
	public $frame = "admin";
	
	public function run() {
		$query = "SELECT
			id,
			name AS '"._("Permissions")."'
			FROM permissions";
		new sqlTable($this, $query, $this->engine->getUrlParam(0));
		new pagination($this, $this->sql->totalRowsCount, $this->engine->getUrlParam(0));
	}

	private function createForm($title) {
		$form = new formConstructor($this, "fileUpload", "", $title);
		$form->addField("name", _("Permission name"), new formString("/^.{0,255}$/"));
		$files = $this->sql->getAssocFromDB("SELECT id, name FROM uploads");
		$form->addField("file_permission", _("File permissions"), new formCheckboxGroup($files, true));
		$form->addField(null, _("Save"), new formSubmit());
		return $form;
	}

	private function save($form, $new=false) {
		if (count($form->errors) == 0) {
			try {
				$postData = $form->getAllValues();

				if ($new) {
					$this->sql->insertIntoTable("permissions", $postData);
				} else {
					$this->sql->updateTable("permissions", $postData, array('id' => intval($this->engine->getUrlParam(0))));
				}
				$this->engine->jump("/admin/permissionsControl/");
			} catch (Exception $e) {
				new pageAlert($this, $e->getMessage());
			}
		} else {
			new pageAlert($this, _("Wrong form filling"));
		}
	}

	public function add() {
		$form = $this->createForm(_("New permission"));
		if ($form->submit()) {
			$this->save($form, true);
		}
		$form->write();
	}

	public function edit() {
		$form = $this->createForm(_("Edit permission"));
		if ($form->submit()) {
			$this->save($form);
		} else {
			$form->setValues($this->sql->getRowFromDB("SELECT name, file_permission FROM permissions WHERE id=".intval($this->engine->getUrlParam(0))));
		}
		$form->write();
	}
	
	public function delete() {
		$this->sql->deleteFromTable("permissions", array("id" => intval($this->engine->getUrlParam(0))));
		$this->engine->jump("/admin/permissionsControl/");
	}
}
?>